<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Service\File;

class Model
{

    public static function save ($fileInfo, $config)
    {
        if (! $config['model'])
        {
            return $fileInfo;
        }
        
        $model = M($config['model']);
        
        $record = $model->where(array(
                'md5' => $fileInfo['md5']
        ))->find();
        
        if ($record)
        {
            // 文件不存在时自动补全
            // 解决数据库中有记录, 但文件不存在时, 上传后不显示图片的问题
            if ($record['path'] && ! file_exists($record['path']))
            {
                $flag=copy($fileInfo['path'], $record['path']);
                if($flag){
                    return $record;
                }
            }
        }
        
        $fileInfo['status'] = 1;
        $fileInfo['create_time'] = date('Y-m-d H:i:s');
        $fileInfo['id'] = $model->data($fileInfo)->add();
        
        if (! $fileInfo['id'])
        {
            throw new \Exception("保存文件记录失败");
        }
        
        return $fileInfo;
    }
}